package com.lixin.web.netty.handler;

import com.lixin.constants.ExceptionConstants;
import com.lixin.exception.*;
import com.lixin.model.response.Response;
import com.lixin.web.netty.NettyServerStarter;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description: 全局异常处理类
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-07-29 18:03:48
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-07-29     张李鑫                     1.0         1.0 Version
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class WebSocketExceptionHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private WebSocketExceptionMapper exceptionMapper;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(), cause);
        NettyServerStarter.ctxThreadLocal.remove();
        WebSocketExceptionMapper.WebSocketExceptionInfo exceptionInfo = exceptionMapper.getExceptionInfo(cause);
        boolean infoIsNull = exceptionInfo != null;


        ctx.writeAndFlush(
                Response.error(
                        infoIsNull ? exceptionInfo.getStatusCode() : -1,
                        infoIsNull ? exceptionInfo.getErrorMessage() : cause.getMessage())
        );
    }
}
